package com.star.gc4.filter;

import com.alibaba.fastjson.JSON;
import com.star.gc4.common.BaseContext;
import com.star.gc4.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*
* 判断用户是否已经登录*/

//@WebFilter(urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    //路径通配符
    public static final AntPathMatcher PATH_MATCHE= new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1.获取到当前uri
        String requestURI = request.getRequestURI();

        //定义不要处理的路径
        String[] urls=new String[]{
                "/*"
                /*"/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs",*/
        };

        //2.判断是否需要处理
        boolean check = check(requestURI,urls);

        //3.如果不需要，则放行
        if(check){
            log.info("{}不需要处理",requestURI);
            filterChain.doFilter(request,response);
            return;
        }

        //4-1.如果已登录，则放行
        Long empId = (Long) request.getSession().getAttribute("employee");
        if (empId !=null){
            //log.info("已登录，用户id为：{}",request.getSession().getAttribute("employee"));
            BaseContext.setThreadLocal(empId);
            filterChain.doFilter(request,response);
            return;
        }
        // 4-2
        Long userId = (Long) request.getSession().getAttribute("user");
        if (userId !=null){
            //log.info("已登录，用户id为：{}",request.getSession().getAttribute("employee"));
            BaseContext.setThreadLocal(userId);
            filterChain.doFilter(request,response);
            return;
        }
        //5.如果未登录，返回未登录结果，页面跳转交给前端
        log.info("用户未登录");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }
    public boolean check(String requestURI,String[] urls){
        for (String url: urls) {
            boolean match = PATH_MATCHE.match(url, requestURI);
            if (match) return true;
        }
        return false;
    }
}
